/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.Country;
import org.cuatrovientos.erp.model.Department;
import org.cuatrovientos.erp.model.IssueType;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Raquel Valenzuela <raquel_valenzuela@cuatrovientos.es>
 *
 */
public class IssueTypeDAO implements IssueTypeDAOInterface {
	
	private SessionFactory sessionFactory;
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	 
	 
	/* selects an issue type by id
	 * @param int id
	 */
	 @Transactional(readOnly = true)
	public IssueType selectById(int id) {
		IssueType issueType = (IssueType) getSession().get(IssueType.class, id);
	    return issueType;
	}

	/* Selects all issue types
	 * @return List of issueTypes
	 */
	 @Transactional(readOnly = true)
	public List<IssueType> selectAll() {
		List<IssueType> issueType = getSession().createQuery("from issueType").list();
	    return issueType;
	}
	 
	 /*
	  * retrieves all issueTypes from db
	  * @return List of issueTypes
	  */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
		 List<IssueType> issueType = getSession().createQuery("from issueType").list();
		 return issueType.size();
	}

	/* 
	 * inserts a new issueType in database
	 * retrieves generated id and sets to issueType instance
	 * @param new issueType
	 * 
	 * */
	@Override
	public void insert(IssueType issueType) {
		Integer id = (Integer) getSession().save(issueType);
	    issueType.setId(id);
	}

	/*  updates an issueType
	 * @param issueType to update
	 */
	@Override
	public void update(IssueType issueType) {
		getSession().merge(issueType);

	}

	/* 
	 * Deletes an Issue Type
	 * @param issueType to delete
	 */
	@Override
	public void delete(IssueType issueType) {
		getSession().delete(issueType);

	}

	/* 
	 * Delete an issue type
	 * @param int id of the issue type to delete
	 */
	@Override
	public void deleteById(int id) {
		IssueType issueType = (IssueType) getSession().load(IssueType.class,id);
		getSession().delete(issueType);

	}

	/* 
	 * Returns the Issue Type with the folowing name
	 * @paran String name
	 * @return Listo of Issue types
	 */
	@Override
	public List<IssueType> search(String name) {
		Query query = getSession().createQuery("from issueType i where i.name like :name");
        query.setParameter("name", "%"+name+"%");
        List<IssueType> issueTypes = query.list();
		
        return issueTypes;
	}

}
